package com.zz.reflection;

import com.zz.Interface.studentMannger.ClassManager;
import org.junit.Test;

import java.lang.reflect.Constructor;
import java.sql.Connection;

/**
 * 目标：掌握获取类的构造器，并对其进行操作
 */
public class Test2Constructor {

    @Test
    public void testGetConstructors() {
        //1.反射第一步:必须先得到这个类的Class对象
        Class c = Student.class;

        //2.获取类的全部构造器
        // Constructor[] constructors = c.getConstructors();只能获取public修饰的构造器
        Constructor[] constructors = c.getDeclaredConstructors();//获取全部构造器--推荐
        //3.遍历数组中的每个构造器对选哪个
        for (Constructor constructor : constructors) {
            System.out.println(constructor.getName() + "===>" + constructor.getParameterCount());
        }
    }

        @Test
        public void testGetConstructor() throws Exception {
            //1.反射第一步:必须先得到这个类的Class对象
            Class c = Student.class;

            //2.获取某个构造器,无参构造器--
            // Constructor constructor = c.getConstructor();只能取到public修饰的构造器
            Constructor constructor = c.getDeclaredConstructor();//可以取到任意修饰符修饰的构造器
            System.out.println(constructor.getName() + "==>" + constructor.getParameterCount());

            constructor.setAccessible(true);//禁止检查访问权限
            //初始化对象
            Student student = (Student)constructor.newInstance();
            System.out.println(student);

            //3.获取有参数的构造器
            Constructor constructor2 = c.getDeclaredConstructor(String.class, int.class);
            System.out.println(constructor2.getName() + "==>" + constructor2.getParameterCount());
            Student student1 = (Student)constructor2.newInstance("小明", 3);
            System.out.println(student1);
        }
}
